#include "MainInterface.hh"
#include "../Utils/include/Common.hh"
#include <iostream>
#include "../Utils/include/json.hpp"
#include "Game.hh"
#include <fstream>
#include <thread>
#include <chrono>

using namespace std;

// 主界面构造函数,初始化玩家、关卡、数据管理器和游戏对象
MainInterface::MainInterface(Player& player, Level& level, DataManager& dm, Game& game)
    : player_(player), level_(level), dataManager_(dm), game_(game) {}

// 主游戏循环
void MainInterface::showLoop() {
    bool running = true;

    while (running) {
        Utility::clearScreen();
        show();        // 展示角色状态
        showMenu();    // 菜单选项

        string choice;
        cin >> choice;

        if (choice == "1") {
            movePlayer();  // 移动玩家
            Utility::clearScreen();

            // 获取并处理当前房间
            int roomID = level_.getCurrentRoomID();
            IRoom* room = dataManager_.getRoom(roomID);
            if (room) {
                room->displayInfo();
                room->enter(&player_);

                // 处理特殊房间和楼层切换
                if (roomID == -1 && level_.hasNextFloor()) {
                    cout << "Preparing to enter the next floor..." << endl;
                    Utility::pause();
                    const auto& nextFloorMap = dataManager_.getFloorMap(level_.getCurrentFloor() + 1);
                    level_.advanceToNextFloor(nextFloorMap);
                } else if (roomID == -2 && level_.hasNextFloor()) {
                    cout << "Preparing to enter the next floor..." <<endl;
                    Utility::pause();
                    const auto& nextFloorMap = dataManager_.getFloorMap(level_.getCurrentFloor() + 1);
                    level_.advanceToNextFloor(nextFloorMap);
                } else if (roomID == -3) {
                    // 显示游戏结束画面
                    Utility::clearScreen();
                    std::vector<std::string> endingText = {
                        "After defeating a powerful enemy...",
                        "You reached the deepest point",
                        "You finally saw the object that attracted you...",
                        "It's a magic dog shit, it doesn't make any sense",
                        "But it does attract everyone who can feel it...",
                        "Suddenly, you realize that your cpp project is about to reach the deadline",
                        "Think of the difficulties you faced and the enemies you killed along the way.",
                        "Looking at this piece of shit, you say:",
                        "███████╗ ██╗   ██╗ ██████╗   ██╗  ██╗",
                        "██╔════╝ ██║   ██║██╔═══██╗  ██║ ██╔╝",
                        "█████╗   ██║   ██║██║        █████╔╝ ",
                        "██╔══╝   ██║   ██║██║        ██╔═██╗ ",
                        "██║      ╚██████╔╝╚██████╗   ██║  ██╗",
                        "╚═╝       ╚═════╝  ╚═════╝   ╚═╝  ╚═╝",
                    };
                    for (const auto& line : endingText) {
                        std::cout << line << std::endl;
                        std::this_thread::sleep_for(std::chrono::seconds(1));
                    }
                    Utility::pause();
                    running = false;
                } else if (level_.isFinished()) {
                    if (level_.hasNextFloor()) {
                        cout << "You have reached the exit of this floor!" << endl;
                        cout << "1. Proceed\n2. Return to the main interface\nPlease choose: ";
                        int c = Utility::getIntInput(1, 2);
                        if (c == 1) {
                            const auto& nextFloorMap = dataManager_.getFloorMap(level_.getCurrentFloor()+1);
                            level_.advanceToNextFloor(nextFloorMap);
                        }
                    } else {
                        // 显示游戏结束画面
                        Utility::clearScreen();
                        std::vector<std::string> endingText = {
                            "After defeating a powerful enemy...",
                            "You reached the deepest point",
                            "You finally saw the object that attracted you...",
                            "It's a magic dog shit, it doesn't make any sense",
                            "But it does attract everyone who can feel it...",
                            "Suddenly, you realize that your cpp project is about to reach the deadline",
                            "Think of the difficulties you faced and the enemies you killed along the way.",
                            "Looking at this piece of shit, you say:",
                            "███████╗ ██╗   ██╗ ██████╗   ██╗  ██╗",
                            "██╔════╝ ██║   ██║██╔═══██╗  ██║ ██╔╝",
                            "█████╗   ██║   ██║██║        █████╔╝ ",
                            "██╔══╝   ██║   ██║██║        ██╔═██╗ ",
                            "██║      ╚██████╔╝╚██████╗   ██║  ██╗",
                            "╚═╝       ╚═════╝  ╚═════╝   ╚═╝  ╚═╝"
                        };
                        for (const auto& line : endingText) {
                            std::cout << line << std::endl;
                            std::this_thread::sleep_for(std::chrono::seconds(1));
                        }
                        Utility::pause();
                        running = false;
                    }
                }
            } else {
                cout << "Room does not exist, data error!" << endl;
                Utility::pause();
            }
        } else if (choice == "2") {
            showBag();  // 显示背包
            Utility::pause();
        } else if (choice == "3") {
            useItem();  // 使用物品
            Utility::pause();
        } else if (choice == "4") {
            saveCurrentGame("Save.json");  // 保存游戏
            cout << "Game progress saved, exiting..." << endl;
            running = false;
        } else {
            cout << "Invalid Choice!" << endl;
            Utility::pause();
        }

        // 检查玩家是否死亡
        if (player_.getHealth() <= 0) {
            cout << "You have died, game over!" << endl;
            running = false;
        }
    }
}

// 显示游戏状态界面
void MainInterface::show() {
    cout << "==============================" << endl;
    cout << "||        CHU-Rogue        ||" << endl;
    cout << "==============================" << endl;
    cout << "Player: " << player_.getName() << endl;
    cout << "HP: " << player_.getHealth() << " / " << player_.getmaxHealth() << endl;
    cout << "ATK: " << player_.getAttack() << "  DEF: " << player_.getDefense() << endl;
    cout << "Position: (" << level_.getPlayerX() << ", " << level_.getPlayerY() << ")" << endl;
    cout << "------------------------------" << endl;
    level_.showSmallMap();
    cout << "------------------------------" << endl;
}

// 显示主菜单选项
void MainInterface::showMenu() {
    cout << "1. Move" << endl;
    cout << "2. CheckBag" << endl;
    cout << "3. UseItems" << endl;
    cout << "4. EXIT" << endl;
    cout << "PlsChoose(1-4): ";
}

// 显示背包内容
void MainInterface::showBag() {
    cout << "===== BAG =====" << endl;
    player_.getInventory().showItems();
}

// 使用物品功能
void MainInterface::useItem() {
    auto& bag = player_.getInventory();
    
    if (bag.isEmpty()) {
        cout << "Bag is empty" << endl;
        return;
    }
    
    bag.showItems();
    cout << "ItemID: ";
    int id;
    cin >> id;
    
    Item* item = bag.findItem(id);
    if (!item) {
        cout << "Not exist!" << endl;
        return;
    }
    
    // 处理不同类型物品的效果
    const string& effect = item->getEffect();
    int value = item->getValue();
    
    if (effect == "heal") {
        player_.heal(value);
        cout << "Used " << item->getName() << ", healed " << value << " HP." << endl;
    } else if (effect == "atk_up") {
        player_.setAttack(player_.getAttack() + value);
        cout << "Used " << item->getName() << ", ATK increased by " << value << "." << endl;
    } else if (effect == "dfc_up") {
        player_.setDefense(player_.getDefense() + value);
        cout << "Used " << item->getName() << ", DEF increased by " << value << "." << endl;
    } else if (effect == "spd_up") {
        player_.setSpeed(player_.getSpeed() + value);
        cout << "Used " << item->getName() << ", SPD increased by " << value << "." << endl;
    } else if (effect == "hp_max_down") {
        player_.setHpMax(player_.getmaxHealth() - value);
        cout << "Used " << item->getName() << ", Max HP decreased by " << value << "." << endl;
    } else {
        cout << "This item's effect is not yet supported." << endl;
    }
    
    bag.removeItem(id);
}

// 处理玩家移动
void MainInterface::movePlayer() {
    auto directions = level_.getAvailableDirections();
    if (directions.empty()) {
        cout << "No EXIT!" << endl;
        return;
    }

    cout << "\nmove derection:" << endl;
    for (size_t i = 0; i < directions.size(); ++i) {
        cout << i + 1 << ". " << level_.directionToString(directions[i]) << endl;
    }

    int choice = Utility::getIntInput(1, directions.size());
    if (!level_.move(directions[choice - 1])) {
        cout << "move failed!" << endl;
        Utility::pause();
    }
}

// 保存游戏进度到文件
void MainInterface::saveCurrentGame(const std::string& path) {
    json j;
    j["player"] = player_;
    j["level"] = level_.toJson();

    std::ofstream out(path);
    if (out.is_open()) {
        out << j.dump(4); // 格式化写入
        out.close();
        std::cout << "Saved as: " << path << std::endl;
    } else {
        std::cerr << "cannot open: " << path << std::endl;
    }
}